<template>
  <div>
    <div style="max-height: 100px;overflow-y: scroll;overflow-x: hidden">
      <el-tree
        ref="tree2"
        :data="layerTree"
        :props="defaultProps"
        :default-expanded-keys="[1]"
        :filter-node-method="filterNode"
        class="filter-tree"
        show-checkbox
        render-after-expand
        highlight-current
        node-key="_id"
        @check="nodeCheck"
      />
    </div>
    <el-input-number
      v-model="bufRadius"
      class="mileagepath"
      placeholder="请输入缓存半径"
      size="small"
      style="width: 100%"
    />

    <div class="mileagepath el-input-number el-input-number--small" style="width: 100%;">
      <span role="button" class="el-input-number__increase" @click="picAction"><i class="el-icon-plus"/></span>
      <div class="el-input el-input--small">
        <input
          v-model="lngAndLat"
          type="text"
          autocomplete="off"
          placeholder="请输入经纬度坐标"
          class="el-input__inner"
          style="padding-left: 0">
      </div>
    </div>

    <hr class="dividingline">

    <el-row>
      <el-button
        class="el-icon-delete font-extras mileagepath"
        type="primary"
        size="small"
        @click="interactiveQuery"
      >查询
      </el-button>
    </el-row>

    <el-row>
      <el-button
        class="el-icon-delete font-extras mileagepath"
        type="warning"
        size="small"
        @click="bufferClear"
      >清除
      </el-button>
    </el-row>

  </div>
</template>

<script>
  import { mapState } from 'vuex'
  import async from 'async/dist/async'
  import Clone from '@/utils/clone'
  import * as turf from '@turf/turf'

  export default {
    name: 'Index',
    data: function() {
      return {
        filterText: '', // 过滤
        defaultProps: {
          children: 'layers',
          label: 'name'
        },
        lngAndLat: '',
        bufRadius: 50,
        startPick: undefined,
        marker: undefined,
        sources: []
      }
    },
    methods: {
      /**
       *
       */
      picAction() {
        this.startPick = true
      },
      /**
       * 图层过滤
       * @param value
       * @param data
       * @returns {boolean}
       */
      filterNode(value, data) {
        if (!value) return true
        return data.name.indexOf(value) !== -1
      },
      /**
       * 交互查询
       */
      interactiveQuery() {
        this.startPick = false
        const selectNodes = this.$refs['tree2'].getCheckedNodes(true, false)

        if (selectNodes.length === 0) {
          this.$message.warning('请勾选要查询的数据!')
          return
        }
        if (this.lngAndLat === '') {
          return
        }
        const array = this.lngAndLat.split(',')
        const clickPoint = new mapboxgl.LngLat(parseFloat(array[0]), parseFloat(array[1]))
        var tasks = []
        for (let i = 0; i < selectNodes.length; i++) {
          const node = selectNodes[i]
          const url = node.url.substring(0, node.url.indexOf('tileFeature') - 1)
          tasks.push(done => {
            const querybyDistanceParam = new SuperMap.QueryByDistanceParameters({
              queryParams: { name: this._parseLayerUrlParam(node.url)['search_layer'] },
              distance: this.bufRadius / 111120, // 米转换成度 let distance = json.properties.radius / 111120
              geometry: clickPoint
            })
            new mapboxgl.supermap.QueryService(url).queryByDistance(querybyDistanceParam, serviceResult => {
                if (!serviceResult.error) { done(undefined, serviceResult, node) }
              }
            )
          })
        }

        async.parallel(tasks, (err, result) => {
          const staticData = []
          for (let i = 0; i < result.length; i++) {
            const e = result[i]
            if (e[0].result.recordsets[0].features.features.length > 0) {
              staticData.push({
                layer: e[1],
                features: e[0].result.recordsets[0].features.features
              })
            }
          }
          this.drawCircleOnMap([parseFloat(array[0]), parseFloat(array[1])], this.bufRadius / 1000)
          this.renderBufferData(staticData)

          // 统计并展示图表
          this.$store.commit('yzt/setBufferStaticsData', staticData)
          this.$store.commit('yzt/setShowBufferStatics', true)
        })
      },
      /**
       * 渲染数据
       * @staticData
       */
      renderBufferData(staticData) {
        this.sources = []
        for (let i = 0; i < staticData.length; i++) {
          const data = staticData[i]
          const id = data.layer._id + '-buf'
          const source = data.layer._id + '-source'
          this.sources.push(source)
          this.mapService.addSource(source) // 添加数据源
          this.mapService.addGeoJsonLayer(id, {
            'id': data.layer._id + '-buf',
            'source': source,
            'type': 'symbol',
            'filter': ['==', '$type', 'Point'],
            'layout': {
              'icon-image': '{layerId}'
            }
          }) // 添加图层
          this.mapService._removeEventListener(id) // 移除事件
          this.mapService._addMouseEventListener(id, data.layer) // 添加事件
          const newData = data.features.map(o => { // 可以再后台配置
            o.properties.layerId = '5cf89161a6258d2c6cbefb11'
            return o
          })
          this.mapService.getMap().getSource(source).setData({
            type: 'FeatureCollection',
            features: newData
          })
        }
      },
      /**
       * 绘制面
       */
      drawCircleOnMap(center, radius) {
        var options = { steps: 200, units: 'kilometers', properties: { foo: 'bar' }}
        var circle = turf.circle(center, radius, options)
        var poly = turf.polygon(circle.geometry.coordinates)
        var line = turf.polygonToLine(poly)
        this.mapService.getMap().getSource('bufferQuery-source').setData({
          type: 'FeatureCollection',
          features: [circle, line]
        })
        const coordinates = line.geometry.coordinates
        const b = new mapboxgl.LngLatBounds(coordinates[0], coordinates[0])
        const bounds1 = coordinates.reduce(function(bounds, coord) {
          return bounds.extend(coord)
        }, b)
        this.mapService.getMap().fitBounds(bounds1, { padding: 100 })
      },

      /**
       * 控制图层开闭
       * @param data
       * @param Node
       */
      async nodeCheck(data, Node) {

      },

      /**
       * 清空数据
       */
      bufferClear() {
        this.mapService.getMap().getSource('bufferQuery-source').setData({ type: 'FeatureCollection', features: [] })
        for (let i = 0; i < this.sources.length; i++) {
          this.mapService.removeLayer(this.sources[i])
         // this.mapService.getMap().getSource(this.sources[i]).setData({type: 'FeatureCollection', features: []})
        }

        if (this.marker) {
          this.marker.remove()
          this.marker = undefined
        }

        // this.mapService.removeGeoJsonLayer('bufferQuery-source-data');
        this.$store.commit('yzt/setShowBufferStatics', false)
        this.$store.commit('yzt/setShowAttribute', undefined)
      },
      /**
       * 解析图层url参数
       * @param url
       * @private
       */
      _parseLayerUrlParam(url) {
        if (url) {
          const urlArray = url.split('?')
          try {
            var obj = JSON.parse(
              '{"' +
              decodeURIComponent(urlArray[urlArray.length - 1])
                .replace(/"/g, '\\"')
                .replace(/&/g, '","')
                .replace(/=/g, '":"') +
              '"}'
            )
          } catch (e) {
            console.warn('图层URL参数配置不正确，不能正常解析的JSON')
            return url
          }
          return obj
        }
      }

    },
    computed: {
      ...mapState({
        /**
         * 图层数据结构
         * @param state
         * @returns {any[]}
         */
        layerTree(state) {
          let layers = []
          state.user.subjectData.forEach(dist => {
            layers = layers.concat(dist.groups)
          })
          return layers.map(o => Clone.clone(o)).filter((o, i, a) => {
            const layers = o.layers.filter(l => {
              const p = this._parseLayerUrlParam(l.url)
              return l.url.indexOf('tileFeature') >= 0 && p && p.search_layer
            })
            o.layers = layers
            return layers.length > 0
          })
        },
        /**
         * 地图服务类
         * @param state
         * @returns {mapService|(function(*))|MapService|*}
         */
        mapService(state) {
          return state.yzt.mapService
        }
      })
    },
    watch: {
      lngAndLat: function(n, o) {
        // 正在匹配
        var reg = /^(\-|\+)?(((\d|[1-9]\d|1[0-7]\d|0{1,3})\.\d{0,6})|(\d|[1-9]\d|1[0-7]\d|0{1,3})|180\.0{0,6}|180)\,(\-|\+)?([0-8]?\d{1}\.\d{0,6}|90\.0{0,6}|[0-8]?\d{1}|90)$/
        if (!reg.test(this.lngAndLat)) {
          return
        }

        const array = this.lngAndLat.split(',')
        if (this.marker) {
          this.marker.setLngLat([parseFloat(array[0]), parseFloat(array[1])])
        } else {
          this.marker = new mapboxgl.Marker()
            .setLngLat([parseFloat(array[0]), parseFloat(array[1])])
            .addTo(this.mapService.getMap())
        }
      }
    },
    mounted: function() {
      // this.mapService.on('click', (e) => {
      //   if (this.startPick) {
      //     this.lngAndLat = e.lngLat.lng.toFixed(6) + ',' + e.lngLat.lat.toFixed(6)
      //   }
      // })
    },
    beforeDestroy: function() {

    }
  }
</script>

<style scoped>
  .buf-query {
    padding: 0;
    margin: 0;
  }

  .buf-query .el-input__inner {
    height: 33px;
    line-height: 33px;
    margin-bottom: 5px;
  }

  .mileagepath {
    margin-bottom: 5px;
    width: 100%;
  }

  .dividingline {
    margin: 15px 7px 5px 8px;;
  }
</style>
